package com.example.enterprise.web;

import com.example.enterprise.exception.InValidateParamException;
import com.example.enterprise.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@Api(tags = "用户信息接口")
@ApiResponses({
        @ApiResponse(code = 200,message = "更新用户成功"),
        @ApiResponse(code = 10001,message = "手机号与密码不可为空"),
        @ApiResponse(code = 12001,message = "手机号已被注册"),
        @ApiResponse(code = 13001,message = "参数错误")
})
@Validated
public class UserController {
    @GetMapping(value = "/user/{id}")
    @ApiOperation(value = "查询单个用户信息",notes = "根据主键查询用户信息")
    @ApiImplicitParam(paramType = "path",name="id",value = "用户主键值",required = true,defaultValue = "1")
    public String getUserById(@PathVariable Integer id) {
        return "/user/" + id;
    }
    @ApiOperation(value = "删除用户信息",notes = "根据主键删除用户")
    @DeleteMapping("/user/{id}")
    @ApiImplicitParam(paramType = "path",name="id",value = "用户主键值",required = true,defaultValue = "1")
    public Integer deleteUserById(@PathVariable Integer id) {
        return id;
    }
    @ApiOperation(value = "添加用户信息",notes = "传入用户名和用户住址添加用户")
    @PostMapping("/user")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name="username",value = "用户名",required = true,defaultValue = "kate"),
            @ApiImplicitParam(paramType = "query",name="address",value = "用户XXX地址",required = true,defaultValue = "马栏山马兰坡"),
    } )
    public String addUser(@Size(min = 6,max = 10,message = "用户名必须在6~8位") String username,
                          String address) throws InValidateParamException {

        return username + ":" + address;
    }
    @ApiOperation(value = "更新用户信息",notes = "修改用户,传入用户信息")
    @PutMapping(value = "/user",produces = "application/json")
    public String updateUser(@RequestBody @Validated User user,BindingResult result) throws JsonProcessingException {
        //1.参数校验
        List<String> errors = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError error : allErrors) {
                errors.add(error.getDefaultMessage());
            }
            return new ObjectMapper().writeValueAsString(errors);
        }
        //2.调用service
        //3.返回响应json
        return user.toString();
    }
    @ApiIgnore
    @GetMapping("/ignore")
    public void ignoreMethod() {
    }
}